package helper

import (
	"anan.iris/conf"
	"github.com/go-xorm/xorm"
	"sync"
	"fmt"
	"log"
)

var (
	masterEngine *xorm.Engine
	slaveEngine  *xorm.Engine
	lock sync.Mutex
)

func InstanceMaster() *xorm.Engine {
	if masterEngine != nil {
		return masterEngine
	}
	lock.Lock()
	defer lock.Unlock()

	if masterEngine != nil {
		return masterEngine
	}
	c := conf.MasterDbConfig
	dsn := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8",c.User,c.Pwd,c.Host,c.Port,c.DbName)
	engine,err := xorm.NewEngine(conf.DriverName,dsn)
	if err != nil{
		log.Fatal("dbhelper.DbInstance error=",err)
		return nil
	}else{
		masterEngine = engine
		return masterEngine
	}
}

func InstanceSlave() *xorm.Engine {
	if slaveEngine != nil {
		return slaveEngine
	}
	lock.Lock()
	defer lock.Unlock()

	if slaveEngine != nil {
		return slaveEngine
	}
	c := conf.SlaveDbConfig
	dsn := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8",c.User,c.Pwd,c.Host,c.Port,c.DbName)
	engine,err := xorm.NewEngine(conf.DriverName,dsn)
	if err != nil{
		log.Fatal("dbhelper.DbInstance error=",err)
		return nil
	}else{
		slaveEngine = engine
		return slaveEngine
	}
}